from django import forms
from django.core.exceptions import ValidationError
from django.http import HttpResponse
from django.shortcuts import render, redirect

from app01 import models
from app01.utils.bootstrap import BootStrapForm
from app01.utils.encrypt import md5
from app01.utils.code import check_code


class LoginForm(BootStrapForm):
    """管理员列表"""

    username = forms.CharField(
        label='用户名',
        max_length=20,
        widget=forms.TextInput,
        required=True
    )
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput,
        required=True
    )
    code = forms.CharField(
        label='验证码',
        widget=forms.TextInput,
        required=True
    )

    def clean_password(self):
        password = self.cleaned_data.get('password')
        return md5(password)


def login(request):
    if request.method == 'GET':
        form = LoginForm()
        return render(request, 'login.html', {'form': form})

    form = LoginForm(request.POST)
    if form.is_valid():
        # username = form.cleaned_data.get('username')
        # password = form.cleaned_data.get('password')
        # print(username, password)
        user_input_code = form.cleaned_data.pop('code')
        session_code = request.session.get('image_code')
        if user_input_code.upper() != session_code.upper():
            form.add_error('code', '验证码错误')
            return render(request, 'login.html', {'form': form})

        # 去数据库校验用户名和密码是否正确，获取用户对象，None
        admin_obj = models.Admin.objects.filter(**form.cleaned_data).first()
        if not admin_obj:
            form.add_error('username', '用户名或密码错误')
            return render(request, 'login.html', {'form': form})
        # 用户名和密码正确
        # 网站生成随机字符串，写到用户浏览器的cookie中，再将用户信息保存到session中
        request.session['user_info'] = {'id': admin_obj.id, 'username': admin_obj.username}
        # 设置session过期时间7天
        request.session.set_expiry(60 * 60 * 24 * 7)
        return redirect('/admin/list/')

    return render(request, 'login.html', {'form': form})


def logout(request):
    request.session.clear()
    return redirect('/login/')


from io import BytesIO


def image_code(request):
    """生成图片验证码"""
    # 1. 调用pillow函数，生成图片验证码
    img, code_str = check_code()
    # 2. 将图片验证码的字符串保存到session中
    request.session['image_code'] = code_str
    # 3. 给Session设置60s超时
    request.session.set_expiry(60)

    stream = BytesIO()
    img.save(stream, 'png')
    return HttpResponse(stream.getvalue())
